﻿using Communicate;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using BaseDll;
using CommonTools;
using UserData;
using System.Xml.Linq;

namespace StationDemo
{
    public class ClibClient
    {
        bool b_heartFlag = false;
        bool b_Islink = false;
        TcpLink Client;
        Thread thread_Recive;
        Thread thread;
        string strIP;
        int nPort;
        bool b_AlreadyEndRecive = false;
        string strEndReciveMsg = "";
        List<string> list_Start = new List<string>();
        List<string> list_Test = new List<string>();
        List<string> list_Stop = new List<string>();

        string name = "";
        public void Init(string strName, string ip, int port)
        {
            name = strName;
            strIP = ip;
            nPort = port;
            Client = new TcpLink(1, "TCP", strIP, nPort, 2000, "");
            Client.Open();
            Client.RecvStringMessageEvent += Recive;
            thread = new Thread(Run);
            thread.IsBackground = true;
            thread.Start();
        }
        private void Connect()
        {
            int _error = 1;
        Retry:
            
            ;
            if (!Client.Open())
            {
                Client.Close();
                if (_error > 1)
                {
                    Thread.Sleep(1000);
                    goto Retry;
                }
                else if (_error > 10)
                {
                    Thread.Sleep(5000);
                    goto Retry;
                }
                else
                {
                    _error = 0;
                    goto Retry;
                }
            }
        }
        private void Run()
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Restart();
            int n_RetryTime = 0;
            while (true)
            {
                try
                {
                    Thread.Sleep(1000);
                    b_heartFlag = false;
                    Send($"HeartBeat");
                    while (true)
                    {
                        if (stopwatch.ElapsedMilliseconds > 3000)
                        {

                            n_RetryTime++;
                            LogHelper.OnTest_ShowLog(name, $"第{n_RetryTime}次未收到心跳，继续获取", UserData.LogType.Warn);
                            if (n_RetryTime < 3)
                                break;
                            else
                            {
                                LogHelper.OnTest_ShowLog(name, $"连续三次获取心跳失败，重新连接服务器", UserData.LogType.Err);
                                b_Islink = false;
                                n_RetryTime = 0;
                                Connect();
                                break;
                            }
                        }
                        if (b_heartFlag)
                        {
                            b_Islink = true;
                            n_RetryTime = 0;
                            break;
                        }

                    }
                }
                catch (Exception e)
                {
                    //LogHelper.OnTest_ShowLog(StationName, $"{e}.ToString()", UserData.LogType.Err);
                }
            }
        }
        string ReceiveAllString = "";
        private void Recive(object sender, AsyTcpSocketEventArgs e)
        {
            try
            {

                ReceiveAllString = ReceiveAllString + e.Message;
                if (!ReceiveAllString.Contains("*"))
                    return;
                string str_Restle = ReceiveAllString.Replace("\r\n", "*");
                string[] s_Restle = str_Restle.Split('*');
                for (int i = 0; i < s_Restle.Length - 1; i++)
                {
                    if (s_Restle[i] == "")
                        continue;
                    if (s_Restle[i].Contains("Heart"))
                    {
                        b_heartFlag = true;
                    }
                    else
                    {
                        LogHelper.OnTest_ShowLog(name, $"TCP接收:{s_Restle[i]}", UserData.LogType.Info);
                    }
                    if (s_Restle[i].Contains("StartFail") || s_Restle[i].Contains("StartOK"))
                    {
                        list_Start.Add(s_Restle[i]);
                    }
                    else if (s_Restle[i].Contains("TestOK") || s_Restle[i].Contains("TestFail"))
                    {
                        list_Test.Add(s_Restle[i]);
                    }
                    else if (s_Restle[i].Contains("StopOK") || s_Restle[i].Contains("StopFail"))
                    {
                        list_Stop.Add(s_Restle[i]);
                    }
                }
                ReceiveAllString = s_Restle[s_Restle.Length - 1];


            }
            catch (Exception eX)
            {
                //  LogHelper.OnTest_ShowLog(StationName, $"{e}.ToString()", UserData.LogType.Err);
            }


        }
        object objLock = new object();
        private void Send(string SendStr)
        {
            lock (objLock)
            {
                Thread.Sleep(100);
                Client.WriteString(SendStr + "*");
                if (!SendStr.Contains("Heart"))
                {
                    LogHelper.OnTest_ShowLog(name, $"TCP发送:{SendStr}", UserData.LogType.Info);
                }

            }
        }
        public bool IsLink()
        {
            return b_Islink;
        }
        public int Cmd_运控平台通知标定平台启动()
        {
            try
            {
                list_Start.Clear();
                Send("StartCmd");
                string str_Recive = "";
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                while (true)
                {
                    if (stopwatch.ElapsedMilliseconds > 10000)
                    {
                        return -2;
                    }
                    Thread.Sleep(20);
                    if (list_Start.Count != 0)
                    {
                        str_Recive = list_Start[0];
                        break;
                    }
                }
                return str_Recive == "StartOK" ? 0 : -1;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return -4;
            }


        }

        public int Cmd_运控平台通知标定平台测试(string str_Cmd, ref string strResult)
        {
            try
            {
                list_Test.Clear();
                Send($"{str_Cmd}");
                string str_Recive = "";
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                while (true)
                {
                    if (stopwatch.ElapsedMilliseconds > 10000)
                    {
                        return -2;
                    }
                    Thread.Sleep(20);
                    if (list_Test.Count != 0)
                    {
                        str_Recive = list_Test[0];
                        break;
                    }
                }
                strResult = list_Test[0];
                return str_Recive == "TestOK" ? 0 : -1;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return -4;
            }


        }
        public int Cmd_运控平台通知标定平台停止()
        {
            try
            {
                list_Stop.Clear();
                Send("StopCmd");
                string str_Recive = "";
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                while (true)
                {
                    if (stopwatch.ElapsedMilliseconds > 10000)
                    {
                        return -2;
                    }
                    Thread.Sleep(20);
                    if (list_Stop.Count != 0)
                    {
                        str_Recive = list_Stop[0];
                        break;
                    }
                }
                return str_Recive == "StopOK" ? 0 : -1;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return -4;
            }


        }



    }

}
